<template>
  <div class="big_box" v-loading="loading">
    <div class="small_box" v-if="isForm">
      <div class="box_title">
        <div>{{ form.deptName }}【{{ form.deptCategory }}】</div>
        <div style="display:flex;align-items: center;gap: 40px;">
          <div>{{ form.phone }}</div>
          <div style="display:flex;align-items: center; color: #34BFA8;cursor: pointer" @click="switchForm">
            <Edit style="width: 1.5em; height: 1.5em;" />
            编辑
          </div>
        </div>
      </div>
      <div>
        <el-row style="width: 100%;padding: 20px 30px 0 30px;">
          <el-col :span="8" class="el_col el_cols">
            <div class="el_col_title">简称</div>
            <div>{{ form.hospitalShortName }}</div>
          </el-col>
          <el-col :span="8" class="el_col el_cols">
            <div class="el_col_title">email</div>
            <div>{{ form.email }}</div>
          </el-col>
          <el-col :span="8" class="el_col el_cols">
            <div class="el_col_title">医院图片</div>
            <div style="width: 65px;height: 65px" v-if="imageList && imageList.length > 0">
              <img :src="imageList && imageList.length > 0? imageList[0].url:''" style="width: 100%;height: 100%"
                   alt="">
            </div>
          </el-col>
        </el-row>
        <el-row style="width: 100%;padding: 20px 30px;">
          <el-col :span="24" class="el_col">
            <div class="el_col_title">医院简介</div>
            <div>{{ form.hospitalIntroduce }}</div>
          </el-col>
        </el-row>
        <el-divider />
        <el-row style="width: 100%;padding: 0 30px;">
          <el-col :span="8" class="el_col el_cols">
            <div class="el_col_title">辖区人口数</div>
            <div style="font-weight: 600">0</div>
          </el-col>
          <el-col :span="8" class="el_col el_cols">
            <div class="el_col_title">辖区重点人口数</div>
            <div style="font-weight: 600">0</div>
          </el-col>
        </el-row>
        <el-divider />
        <el-row style="width: 100%;padding: 0 30px 0 30px;">
          <el-col :span="24" class="el_col el_cols">
            <div class="el_col_title">详细地址</div>
            <div>{{ form.detailAddress }}</div>
          </el-col>
        </el-row>
        <el-row style="width: 100%;padding: 20px 30px 0 30px;">
          <el-col :span="24" class="el_col el_cols">
            <div class="el_col_title">经纬度</div>
            <div>{{ form.longitude }}&emsp;&emsp;&emsp;&emsp;{{ form.latitude }}</div>
          </el-col>
        </el-row>
        <el-row style="width: 100%;padding: 20px 30px 0 30px;">
          <el-col :span="24" class="el_col el_cols">
            <div id="container"></div>
          </el-col>
        </el-row>
        <!--        <el-divider />-->
      </div>
    </div>


    <div class="editForm" v-else>
      <div style="width: 700px">
        <el-form ref="formRef" :model="form" label-width="150px" :rules="rule">
          <el-form-item label="医院名称：" prop="deptName">
            <el-input v-model="form.deptName" clearable />
          </el-form-item>
          <el-form-item label="上级机构：" prop="parentId">
            <el-input v-model="form.parentName" style="width: 100%;" disabled />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="医院电话：" prop="phone">
                <el-input v-model="form.phone" style="width: 100%;" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="医院简称：" prop="hospitalShortName">
                <el-input v-model="form.hospitalShortName" style="width: 100%;" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="所属地区：">
            <div style="width: 100%;display: flex;gap: 5px">
              <el-select
                v-model="selectedRegion[0]"
                placeholder="请选择省份"
                @change="updateRegion(1)"

              >
                <el-option
                  v-for="option in currentOptions[0]"
                  :key="option.code"
                  :label="option.name"
                  :value="option.code"
                />
              </el-select>
              <el-select
                v-model="selectedRegion[1]"
                placeholder="请选择市"
                @change="updateRegion(2)"
              >
                <el-option
                  v-for="option in currentOptions[1]"
                  :key="option.code"
                  :label="option.name"
                  :value="option.code"
                />
              </el-select>
              <el-select
                v-model="selectedRegion[2]"
                placeholder="请选择区/县"
                @change="updateRegion(3)"
              >
                <el-option
                  v-for="option in currentOptions[2]"
                  :key="option.code"
                  :label="option.name"
                  :value="option.code"
                />
              </el-select>
              <el-select
                v-model="selectedRegion[3]"
                placeholder="请选择街道"
                @change="updateRegion(4)"
              >
                <el-option
                  v-for="option in currentOptions[3]"
                  :key="option.code"
                  :label="option.name"
                  :value="option.code"
                />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="Email：" prop="email">
            <el-input v-model="form.email" clearable />
          </el-form-item>
          <el-form-item label="医院图片：" prop="userId">
            <image-upload :limit="1" v-model="form.hospitalImage"></image-upload>
          </el-form-item>
          <el-form-item label="医院介绍：" prop="hospitalIntroduce">
            <el-input type="textarea" v-model="form.hospitalIntroduce" clearable />
          </el-form-item>
          <el-form-item label="辖区人口数：" prop="userId">
            <el-input v-model="form.userId" placeholder="请在“人口基数管理”模块中进行维护" disabled />
          </el-form-item>
          <el-form-item label="辖区重点人口数：" prop="userId">
            <el-input v-model="form.userId" placeholder="请在“人口基数管理”模块中进行维护" disabled />
          </el-form-item>
          <el-form-item label="详细地址：" prop="detailAddress">
            <el-input v-model="form.detailAddress" id="tipinput" clearable>
              <template #append>
                <el-button icon="Location" @click="searchLocation" />
              </template>
            </el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="经度：" prop="longitude">
                <el-input v-model="form.longitude" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度：" prop="latitude">
                <el-input v-model="form.latitude" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="地图：">
            <div>
              <div id="container"></div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
            <el-button @click="switchForm">取 消</el-button>
          </el-form-item>

        </el-form>
      </div>
    </div>

  </div>
</template>

<script>

import AMapLoader from '@amap/amap-jsapi-loader';
import useUserStore from '@/store/modules/user';
import { getDept, updateDept } from '@/api/system/dept/index';
import { getMapData } from '@/api/workflow/gaodeMap/index';
import { getBasicPublicRegion, listBasicPublicRegion } from '@/api/basicPublic/basicPublicRegion/index';
import { listByIds } from '@/api/system/oss/index';

export default {
  name: 'PublicHealthTable',
  data() {
    return {
      map: undefined,
      map1: undefined,
      queryParams: {
        deptId: undefined
      },
      isForm: true,
      form: {},
      buttonLoading: false,
      loading: false,
      rule: {
        deptName: [{ required: true, message: '医院名称不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '医院电话不能为空', trigger: 'blur' }],
        hospitalShortName: [{ required: true, message: '医院简称不能为空', trigger: 'blur' }],
        detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
        hospitalImage: [{ required: true, message: '医院图片不能为空', trigger: 'blur' }],
        longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
        latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }]
      },
      geocoder: undefined,
      selectedRegion: ['', '', '', ''],
      currentOptions: [[], [], [], []],
      imageList: []
    };
  },
  created() {
    this.getDepts();
  },
  mounted() {
    // 初始化时调用 updateRegion 来更新 currentOptions
    this.updateRegion(0);
  },
  methods: {
    maps() {
      AMapLoader.load({
        key: import.meta.env.VITE_APP_MAP_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.map = new AMap.Map('container', {
          // 设置地图容器id
          viewMode: '3D', // 是否为3D地图模式
          zoom: 17, // 初始化地图级别
          center: [this.form.longitude, this.form.latitude] // 初始化地图中心点位置
        });

        const position = new AMap.LngLat(this.form.longitude, this.form.latitude); //Marker 经纬度
        const marker = new AMap.Marker({
          icon: `${import.meta.env.VITE_IMAGE_PATH}/mapimages/map_icon.png`,
          position: position,
          // content: markerContent,
          offset: new AMap.Pixel(-16, -45) //以 icon 的 [center bottom] 为原点
        });
        this.map.add(marker);
      }).catch((e) => {
        console.log(e);
      });
    },

    async getDepts() {
      this.loading = true;
      try {
        this.queryParams.deptId = useUserStore().deptId;
        const res = await getDept(this.queryParams.deptId);
        this.form = res.data;
        if (this.form.hospitalImage) {
          const imageUrl = await listByIds(this.form.hospitalImage);
          this.imageList = imageUrl.data;
        }
        this.selectedRegion = [
          this.form.provinceCode,
          this.form.cityCode,
          this.form.areaCode,
          this.form.streetCode
        ];

        await this.fetchRegionOptions(1, this.form.provinceCode);
        await this.fetchRegionOptions(2, this.form.cityCode);
        await this.fetchRegionOptions(3, this.form.areaCode);

        this.maps();
        this.loading = false;
      } catch (error) {
        console.error('获取部门信息失败:', error);
      }
    },

    async fetchRegionOptions(index, parentCode) {
      if (parentCode) {
        try {
          const res = await getBasicPublicRegion({ parentCode });
          this.currentOptions[index] = res.data;
        } catch (error) {
          console.error(`获取区域选项失败 (index: ${index}, parentCode: ${parentCode}):`, error);
        }
      }
    },

    switchForm() {
      this.isForm = !this.isForm;
      this.maps();
    },

    submitForm() {
      this.form.provinceCode = this.selectedRegion[0];
      this.form.cityCode = this.selectedRegion[1];
      this.form.areaCode = this.selectedRegion[2];
      this.form.streetCode = this.selectedRegion[3];


      this.$refs['formRef'].validate(valid => {
        if (valid) {
          updateDept(this.form).then(res => {
            this.$modal.msgSuccess('保存成功');
            this.getDepts();
            this.switchForm();
          });
        }
      });
    },


    searchLocation() {
      let a = {
        address: this.form['detailAddress'],
        key: import.meta.env.VITE_APP_MAP_WEB_KEY,
        output: 'json'
      };
      getMapData(a).then(res => {
        if (res['info'] === 'OK' && res['geocodes'].length > 0) {
          this.form.longitude = res['geocodes'][0].location.split(',')[0];
          this.form.latitude = res['geocodes'][0].location.split(',')[1];
          this.maps();
        }
      });
    },


    updateRegion(index) {
      // 清除后续的选择
      this.selectedRegion.splice(index);
      let Data1 = {
        level: 1
      };
      let Data2 = {
        parentCode: undefined
      };
      if (index == 0) {
        listBasicPublicRegion(Data1).then(res => {
          this.currentOptions[index] = res.rows;
        });
      } else {
        if (this.options) {
          Data2.parentCode = this.options.streetCode;
        } else {
          Data2.parentCode = this.selectedRegion[index - 1];
        }
        listBasicPublicRegion(Data2).then(res => {
          this.currentOptions[index] = res.rows;
        });
      }
    }

  }
};
</script>

<style scoped lang="scss">
.big_box {
  height: 90.5vh;
  padding: 20px;
  font-size: 14px;
  background: white;
  border-radius: 10px 10px 0 0;
  margin: 20px;
  overflow: scroll;

  .small_box {
    border: 1px solid #F5F5F5;
    height: 100%;
    border-radius: 10px;
    overflow: hidden;

    .box_title {
      height: 60px;
      background: #F0F1F5;
      display: flex;
      font-size: 16px;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      font-weight: 600;
    }
  }

  .editForm {
    display: flex;
    justify-content: center;
    background: white;


  }
}

.el_col {
  display: flex;
  align-items: center;
}

.el_cols {
  align-items: normal;
}

.el_col_title {
  width: 130px;
  color: #555555;
}

#container {
  width: 500px;
  height: 300px;
}

</style>
